package com.lagou.controller;

import com.aliyun.oss.model.OSSObject;
import com.lagou.bean.UpLoadResult;
import com.lagou.service.FileUpLoadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/oss")
public class OssController {
    @Autowired
    private FileUpLoadService fileUpLoadService;
    @PostMapping("/upload")
    @ResponseBody
    public UpLoadResult upload(@RequestParam("file") MultipartFile multipartFile){
        float size = (float) multipartFile.getSize() / 1024 / 1024;
        if(size > 5){ //大于5,M
            UpLoadResult upLoadResult = new UpLoadResult();
            upLoadResult.setStatus("error");
            upLoadResult.setResponse("上传文件大小超过了5M");
            return upLoadResult;
        }
        return  fileUpLoadService.upload(multipartFile);
    }

    @GetMapping("/download")
    @ResponseBody
    public void download(HttpServletResponse response,@RequestParam("objectName") String objectName){
        try{
            OSSObject ossObject = fileUpLoadService.download(objectName);
            if(ossObject==null){
                response.setStatus(400);
                OutputStream os = response.getOutputStream();
                os.write("无法获取指定objectName,请检查是否有对应文件".getBytes());
                os.flush();
                os.close();
                return;
            }
            String fileName = StringUtils.substringAfterLast(objectName, "/");
            InputStream in = ossObject.getObjectContent();
            /* 设置文件ContentType类型，这样设置，会自动判断下载文件类型 */
            response.setContentType("multipart/form-data");
            /* 设置文件头：最后一个参数是设置下载文件名 */
            response.setHeader("Content-Disposition", "attachment;filename="+fileName);
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while((len = in.read(b)) > 0){
                os.write(b,0,len);
            }
            os.flush();
            os.close();
            in.close();
        }catch (IOException ioe){
            ioe.printStackTrace();
        }
    }

    @GetMapping("/delete")
    @ResponseBody
    public String delete(HttpServletResponse response,@RequestParam("objectName") String objectName){
        boolean delete = fileUpLoadService.delete(objectName);
        if(delete){
            return "删除成功";
        }else{
            return "删除失败，没有找到对应文件";
        }
    }
}
